<?php

/**
 * @author Nguyen Thai Binh
 */
if (!defined('BASEPATH'))
  exit('No direct script access allowed');

class Login extends CI_Controller {

  public function __construct() {
    parent::__construct();
    set_userdata('currentURL', current_url());
  }

  public function index() {
    if (userdata('username')) {
      redirect('admin/index');
    } else {
      $this->load->view('admin/login');
    }
  }

  private function _validate($username, $password) {
    $user_message = '';
    if (empty($username)) {
      $user_message = $this->lang->line('error.login.username.require');
    } else if (strlen($username) < 3) {
      $user_message = $this->lang->line('error.login.minimum', 3);
    } else if (!validate_alphanumeric_underscore($username)) {
      $user_message = $this->lang->line('error.login.username.invalid', $username);
    }

    $password_message = '';
    if (empty($password)) {
      $password_message = $this->lang->line('error.login.password.require');
    } else if (strlen($password) < 6) {
      $password_message = $this->lang->line('error.login.minimum', 6);
    }
    if (!empty($user_message) || !empty($password_message)) {
      return '[' . (empty($user_message) ? '' : '["username",false,"' . $user_message . '"]') .
      (!empty($user_message) && !empty($password_message) ? ',' : '') .
      (empty($password_message) ? '' : '["password",false,"' . $password_message . '"]') . ']';
    }
    return '';
  }

  public function process() {
    $username = isset($_REQUEST['username']) ? $_REQUEST['username'] : '';
    $password = isset($_REQUEST['password']) ? $_REQUEST['password'] : '';
    $errors = $this->_validate($username, $password);
    if (empty($errors)) {
      $user = $this->user_model->get(array('username' => $username, 'is_active' => true));
      if (!empty($user)) {
        $password = md5($user['salt'] . md5($password));
        if ($user["password"] == $password) {
          $user['last_login'] = time();
          unset($user['password']);
          $this->user_model->save($user);
          $this->auth->session_login($user);
          echo '[]';
          return;
        }
      }
      echo '[["password",false,"' . $this->lang->line('error.login.password.incorrect') . '"]]';
    } else
      echo $errors;
  }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */